package com.wen.rabbitmq.pubsub;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {

    public static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("120.26.47.111");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");

            //获取队列的名称
            final String queueName = Thread.currentThread().getName();
            Connection connection =null;
            Channel channel = null;
            try{
                connection = connectionFactory.newConnection("生产者");
                //3.通过连接获取通道channel
                channel = connection.createChannel();
                Channel finalChannel = channel;
                finalChannel.basicConsume(queueName, true, new DeliverCallback() {
                    @Override
                    public void handle(String s, Delivery delivery) throws IOException {
                        System.out.println("接收到的消息是" + new String(delivery.getBody(), "utf-8"));
                    }
                }, new CancelCallback() {
                    @Override
                    public void handle(String s) throws IOException {
                        System.err.println("接受失败了");
                    }
                });
                System.err.println("开始接受消息");
                System.in.read();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //7.关闭通道
                if(channel!=null && channel.isOpen()){
                    try {
                        channel.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                //8.关闭连接
                if(connection!=null && connection.isOpen()){
                    try {
                        connection.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    };



    public static void main(String[] args) {
        new Thread(runnable,"queue1").start();
        new Thread(runnable,"queue2").start();
        new Thread(runnable,"queue3").start();
        new Thread(runnable,"queue4").start();
    }

}
